package com.dk.lock;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

@Component
public class CurrentLock {

    /** redis 命令是原子性
     *
     * setnx 如果没有key 放进去，有返回，false
     *
     * getset 取旧赋新
     * */

    @Resource
    private RedisTemplate redisTemplate;

    public boolean lock (String key,String value){
        /*setnx*/
        if (redisTemplate.boundValueOps(key).setIfAbsent(value)) {
            return true;
        }

        /** ，避免锁超时而导致的死锁问题*/

        String oldValue = (String) redisTemplate.boundValueOps(key).get();
        if (StringUtils.isNoneBlank(oldValue) && Long.parseLong(oldValue) < System.currentTimeMillis()){

            //取旧赋新，原子性
            String oldValue2 = (String) redisTemplate.boundValueOps(key).getAndSet(value);
            if (Objects.equals(oldValue,oldValue2)){
                return true;
            }
        }
        return false;
    }

    /** 解锁*/
    public boolean unlock(String key,String value){
        try {
            String oldValue = (String) redisTemplate.boundValueOps(key).get();
            if (Objects.equals(oldValue,value)) {
                redisTemplate.delete(key);
            }
            return true;
        }catch (Exception e){
            return false;
        }
    }
}
